const fsUtil = require("./util/lw-fs");
const http = require('http');
var request = require('request-promise');


requestMatchDugisInfoTest();
// httpMatchDugisInfoTest();


// 异步写文件测试
async function requestMatchDugisInfoTest() {
    console.log("===============requestMatchDugisInfoTest=================")
    // 同步读取csv文件
    let datas = fsUtil.fsReadCsvFileDatasSync("files/market_xy.csv");
    // console.log(datas.length);
    // datas.length = 500;
    let successCount = 0;
    let nullCount = 0;
    let notCommCount = 0;
    let errorCount = 0;
    for (let i = 0; i < datas.length; i++) {
        if((i+1)%30==0) {
            await sleep(3000);
        }

        let lon = datas[i].split(",")[0]
        let lat = datas[i].split(",")[1]

        // http://10.236.20.81:7005/dataservice/locAoi?loc=110.389444,21.215567
        var options = {
            method: 'GET',
            url: 'http://10.236.20.81:7005/dataservice/locAoi?loc=' + lon + ',' + lat,
            // json: true,
            headers: {
                'Connection': 'keep-alive',
                'Accept-Encoding': '',
                'Accept-Language': 'en-US,en;q=0.8'
            }
        };
        // console.log(options)
        request(options)
            .then(data => {
                // console.log(data);
                let resData = JSON.parse(data);
                // console.log(index++, resData.result.aoiVOList);
                if (resData.status === 0) {
                    // console.log(resData)
                    if(!resData.result.aoiVOList || resData.result.aoiVOList.length == 0) {
                        nullCount++
                        return;
                    }
                    for (let i = 0; i < resData.result.aoiVOList.length; i++) {
                        let aoiVO = resData.result.aoiVOList[i]
                        if(aoiVO.className == '住宅区' || aoiVO.className == '住宅小区') {
                            successCount++
                            // console.log(aoiVO)
                            let content = lon + "," + lat + "," + aoiVO.id + "," + aoiVO.name + "," + aoiVO.address
                            console.log("成功返回第<" + successCount + ">次。获取内容：" + content)
                            // update hxtt_target_market_info set address = '罗湖东湖路11',du_comm_id = 'aa',du_comm_name = 'aa' where market_id in (select market_id from hxtt_border_data where border_type = '1' and longitude = '114.1378591' and latitude = '22.5849097');
                            let sql = "update hxtt_target_market_info set address = '" + aoiVO.address + "',du_comm_id = '" + aoiVO.id + "',du_comm_name = '" + aoiVO.name + "' where market_id in (select market_id from hxtt_border_data where border_type = '1' and longitude = '" + lon + "' and latitude = '" + lat + "');";
                            // 同步追加写入文件
                            fsUtil.fsAppendFileSync("files/market_xy_matched.txt", content + "\n");
                            fsUtil.fsAppendFileSync("files/market_xy_matched_sql.txt", sql + "\n");
                        } else {
                            notCommCount++
                        }
                    }
                }
            })
            .catch(error => {console.log(error); errorCount++})

    }
    await sleep(5000);
    console.log("最终总共请求<" + (successCount + nullCount + notCommCount + errorCount) + ">次。成功返回数据<" + successCount + ">次。返回非小区数据<" + notCommCount + ">此。返回为空数据<" + nullCount + ">次。返回异常<" + errorCount + ">次")
}


// 异步写文件测试
function httpMatchDugisInfoTest() {
    console.log("===============httpMatchDugisInfoTest=================")
    // 同步读取csv文件
    let datas = fsUtil.fsReadCsvFileDatasSync("files/market_xy.csv");
    // console.log(datas);
    // const keepAliveAgent = new http.Agent({keepAlive: true});
    // for (let i = 0; i < datas.length; i++) {
    for (let i = 0; i < datas.length; i++) {
        let lon = datas[i].split(",")[0]
        let lat = datas[i].split(",")[1]
        // 10.236.20.81:7005/dataservice/locAoi?loc=110.389444,21.215567
        http.get({
            hostname: '10.236.20.81',
            port: 7005,
            path: 'http://10.236.20.81:7005/dataservice/locAoi?loc=' + lon + ',' + lat,
            // agent: keepAliveAgent
        }, (res) => {
            // 使用响应做些事情
            // console.log(res);
            if (res.statusCode === 200) {
                res.setEncoding("utf-8");
                res.on("data", function (chunk) {
                    // console.log(chunk.toString())
                    let resData = JSON.parse(chunk);
                    if (resData.status === 0) {
                        // console.log(resData)
                        if(!resData.result.aoiVOList || resData.result.aoiVOList.length == 0) {
                            return;
                        }
                        for (let i = 0; i < resData.result.aoiVOList.length; i++) {
                            let aoiVO = resData.result.aoiVOList[i]
                            if(aoiVO.className == '住宅区' || aoiVO.className == '住宅小区') {
                                // console.log(aoiVO)
                                let content = lon + "," + lat + "," + aoiVO.id + "," + aoiVO.name + "," + aoiVO.address + "\n"
                                // console.log(content)
                                // update hxtt_target_market_info set address = '罗湖东湖路11',du_comm_id = 'aa',du_comm_name = 'aa' where market_id in (select market_id from hxtt_border_data where border_type = '1' and longitude = '114.1378591' and latitude = '22.5849097');
                                let sql = "update hxtt_target_market_info set address = '" + aoiVO.address + "',du_comm_id = '" + aoiVO.id + "',du_comm_name = '" + aoiVO.name + "' where market_id in (select market_id from hxtt_border_data where border_type = '1' and longitude = '" + lon + "' and latitude = '" + lat + "');";
                                sql += "\n"
                                // 同步追加写入文件
                                fsUtil.fsAppendFileSync("files/market_xy_matched.txt", content);
                                fsUtil.fsAppendFileSync("files/market_xy_matched_sql.txt", sql);
                            }
                        }
                    }
                });
                res.on('error', function (e) {
                    console.error(`请求遇到问题: ${e.message}`);
                })
            } else {
                console.log("http请求失败：" + res.statusMessage)
            }
        });
    }
}


function sleep (time) {
    return new Promise((resolve) => setTimeout(resolve, time));
}


